#pragma once
#include <string>
#include <map>
#include <atlimage.h>

namespace bs
{
	class Config;

	class ImageManager
	{
	public:
		static ImageManager& Instance();

		CImage* GetImage(const char* name, bool mirror = false);
		void ReleaseImage(CImage* image);

		void SetConfigFile(const char* file = "image.ini");

	private:
		ImageManager();
		~ImageManager();

	private:
		struct ImageInfo
		{
			ImageInfo(CImage* newImage) { ref = 1; image = newImage; }
			~ImageInfo() { if(image) delete image; }

			CImage* GetImage() { ++ref; return image; }
			bool Release()         
			{ 
				--ref; 
				if(ref<=0) 
				{
					delete image;
					image = NULL;
					return true;
				}

				return false;
			}

			bool IsNull() { return image==NULL; }

			CImage* image;
			int ref;
		};

	private:
		CImage* GetImage(const char* name, std::map<std::string, ImageInfo*>& imageMap, bool mirror);

	private:
		std::map<std::string, ImageInfo*> images;
		std::map<std::string, ImageInfo*> mirrors;
		Config* cfg;
	};

}
